package com.zky.gulimall.ssoserver.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @Description TODO
 * @Author 张开源
 * @Date 2022/11/30 22:05
 * @Version 1.0
 **/
@Controller
@Slf4j
public class loginController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @ResponseBody
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("token") String token){
        return stringRedisTemplate.opsForValue().get(token);
    }

    /**
     * 登录
     *
     * @return
     */
    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url") String url, Model model,
                            @CookieValue(value = "sso_token",required = false) String sso_token) {
        log.warn("redirect_url"+url);
        if(!StringUtils.isEmpty(sso_token)){
            //说明有人登陆过，浏览器有记录了直接跳回去要跳转的值
            return "redirect:" + url + "?token=" + sso_token;
        }
        model.addAttribute("url", url);
        return "login";
    }

    /**
     * 登录
     *
     * @return
     */
    @PostMapping("/doLogin")
    public String doLogin(@RequestParam("userName") String userName,
                          @RequestParam("password") String password,
                          @RequestParam("url") String url,
                          HttpServletResponse response) {
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
            //登陆失败
            return "login";
        }
        log.warn("login success,will redirect new Url");
        //存储用户登陆信息
        String uuid = UUID.randomUUID().toString().replace("-", "");
        stringRedisTemplate.opsForValue().set(uuid, userName);
        response.addCookie(new Cookie("sso_token",uuid));
        //登陆成功
        return "redirect:" + url + "?token=" + uuid;
    }
}
